<template>
	<view class="container">
		<u-empty mode="data" icon="../../static/dataEmpty.png" v-if="examList.length==0">
		</u-empty>
		<template v-else>
			<view class="time_container">
				剩余时间
				<u-count-down :time="initTime * 60 * 1000" format="HH:mm:ss" autoStart millisecond @change="onChange"
					@finish="timeFinsh">
					<view class="time">
						<view class="time__custom"
							:style="{background: (timeData.hours==0&&timeData.minutes>=10) ?'green':'red'}">
							<text
								class="time__custom__item">{{ timeData.hours>10?timeData.hours:'0'+timeData.hours}}</text>
						</view>
						<text class="time__doc"
							:style="{color: (timeData.hours==0&&timeData.minutes>=10) ?'green':'red'}">:</text>
						<view class="time__custom"
							:style="{background: (timeData.hours==0&&timeData.minutes>=10) ?'green':'red'}">
							<text
								class="time__custom__item">{{ timeData.minutes>=10?timeData.minutes:'0'+timeData.minutes }}</text>
						</view>
						<text class="time__doc"
							:style="{color: (timeData.hours==0&&timeData.minutes>=10) ?'green':'red'}">:</text>
						<view class="time__custom"
							:style="{background: (timeData.hours==0&&timeData.minutes>=10) ?'green':'red'}">
							<text
								class="time__custom__item">{{ timeData.seconds>=10?timeData.seconds:'0'+timeData.seconds }}</text>
						</view>
					</view>
				</u-count-down>
			</view>
			<view class="main_content" @touchstart="touchStart" @touchend="touchEnd">
				<view class="layout-between questTypeContent">
					<view class="questionType">{{questionType}}题</view>
					<view class="questionAmount">
						<view>
							<text class="activeClr">{{currentNum}}</text>/{{examList.length}}
						</view>
					</view>
				</view>
				<view class="questionContent">
					<view class="questionTitle">
						<view v-html="currentQuestion.stem"></view>
					</view>
					<view class="answer_item" v-if="currentQuestion.type == 1">
						<u-radio-group v-model="userAnswer.answer" placement="column" @change="groupChange"
							:labelSize="30" inactiveColor="#000" activeColor="#3888FF">
							<u-radio :customStyle="{marginBottom: '12px'}"
								v-for="(item, index) in currentQuestion.options" :key="index" :label="item.label"
								:name="item.value">
							</u-radio>
						</u-radio-group>
					</view>
					<template v-else-if="currentQuestion.type == 3">
						<u-radio-group v-model="userAnswer.answer" placement="column" @change="groupChange"
							:labelSize="30" inactiveColor="#000" activeColor="#3888FF">
							<u-radio name="A" label="正确" :customStyle="{marginBottom: '12px'}"></u-radio>
							<u-radio name="B" label="错误" :customStyle="{marginBottom: '12px'}"></u-radio>
						</u-radio-group>
					</template>
					<template v-else-if="currentQuestion.type == 2">
						<u-checkbox-group v-model="userAnswer.answer" placement="column" @change="checkboxChange">
							<u-checkbox :customStyle="{marginBottom: '8px'}"
								v-for="(item, index) in currentQuestion.options" :key="index" :label="item.label"
								:name="item.value">
							</u-checkbox>
						</u-checkbox-group>
					</template>
				</view>
			</view>
			<view class="bottom_area">
				<u-row>
					<u-col span="3">
						<view class="answerSheet" @click="preNextClick(-1)">
							<image src="../../static/previous.png"></image>
							<view>上一题</view>
						</view>
					</u-col>
					<u-col span="3">
						<view class="answerSheet" @click="preNextClick(1)">
							<image src="../../static/next.png"></image>
							<view>下一题</view>
						</view>
					</u-col>
					<u-col span="3">
						<view class="answerSheet" @click="onAnswerSheet">
							<image src="../../static/answerSheet.png"></image>
							<view>答题卡</view>
						</view>
					</u-col>
					<u-col span="3">
						<view class="submitBtn">
							<u-button text="提交试卷" color="linear-gradient(to right, #7774ff, #017ffd,#01b1fd)"
								@click="toSubmit(examList)"></u-button>
						</view>
					</u-col>
				</u-row>
			</view>
		</template>
		<u-popup :show="showAnswerSheet" mode="bottom" @close="closeAnswer" @open="openAnswer">
			<view class="answerPanel">
				<view class="layout-between">
					<view class="card_title">答题卡</view>
					<view>
						<text class="titleTxt">
							未做
							<i class="titleText"></i>
						</text>
						<text class="titleTxt">
							已做
							<i class="titleText titleAnswered"></i>
						</text>
					</view>
				</view>
				<view class="card_content">
					<view v-for="(item,index) in examList" :key="index" @click="onAnswerPanel(index)"
						:class="{'picker-item':true,normal:item.stuAnswer.length>0}">
						{{index+1}}
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	const _ = require("lodash")
	import {
		forEach
	} from "lodash"
	import {
		startExam,
		submitJob,
	} from "../../utils/api.js"
	export default {
		data() {
			return {
				examList: [],
				isLoading: false,
				currentNum: 1,
				timeData: {},
				initTime: null,
				userAnswer: [{
					answer: '',
					questionId: ''
				}],
				showAnswerSheet: false,
				testPaperId: null, //试卷规则的id
				userId: null,
				startX: 0, // 滑动开始x轴位置
			}
		},
		onLoad(option) {
			this.testPaperId = option.id
			this.initTime = option.duration
			this.userId = uni.getStorageSync('userinfo').id
			this.getExamList()
		},
		onBackPress(options) {
			let that = this
			if (options.from === 'backbutton' && that.examList.length > 0) {
				uni.showModal({
					title: '提示',
					content: '现在离开页面，将自动提交试卷',
					success: function(res) {
						if (res.confirm) {
							//自动交卷							
							that.toSubmit(that.examList)
						} else if (res.cancel) {}
					}
				});
				return true
			} else {
				return false
			}
		},
		methods: {
			toSubmit(list) {
				let that = this
				uni.showModal({
					title: '提示',
					content: '您确定要提交试卷吗，提交后将不能再更改。',
					success: function(res) {
						if (res.confirm) {
							let sExamList = JSON.stringify(list)
							for (let i = 0; i < list.length; i++) {
								if (typeof list[i].stuAnswer == 'object') {
									list[i].stuAnswer = list[i].stuAnswer.toString()
								}
							}
							submitJob({
								userId: that.userId,
								id: parseInt(that.testPaperId),
								userAnswer: that.userAnswerParams
							}).then(s => {
								if (s.code === 20000) {
									uni.navigateTo({
										url: `/pages/onlineTesting/examinationResults?examParam=${JSON.stringify(s.data.question)}&resultParam=${JSON.stringify(s.data.answer)}`
									})

								} else {
									uni.showToast({
										title: s.message,
										icon: "none"
									})
								}
							})
						} else if (res.cancel) {
							// console.log('用户点击取消');
						}
					}
				});
			},
			onChange(e) {
				this.timeData = e
				// console.log("倒计时change",e);
			},
			timeFinsh() {
				uni.showToast({
					title: '时间到，强制交卷',
					icon: 'none',
					duration: 1500
				})
				this.toSubmit(this.examList)
			},
			groupChange(n) {
				this.examList[this.currentNum - 1].stuAnswer = this.userAnswer.answer
				// let _this = this
				// setTimeout(() => {
				// 	_this.preNextClick(1)
				// }, 1000)
			},
			checkboxChange(n) {
				this.examList[this.currentNum - 1].stuAnswer = n
			},
			//上一题，下一题
			preNextClick(p) {
				if (this.examList.length === this.currentNum) {
					//最后一题，提示直接提交？
					if (p == 1) { //下一题
						uni.showToast({
							title: '当前是最后一题',
							icon: 'none',
							duration: 1500
						})
					}
				}

				this.currentNum = Math.max(1, Math.min(this.currentNum + p, this.examList.length))
			},
			getCurrentQuestion() {
				const data = _.cloneDeep(this.examList).find((_, i) => i === this.currentNum - 1) || {}
				data.options = Object.entries(data.options || {}).map(([key, value]) => ({
					label: key + "、" + value,
					value: key
				}))
				data.options = data.options
				return data
			},
			openAnswer() {
				// this.$forceUpdate()
			},
			closeAnswer() {
				this.showAnswerSheet = false
			},
			onAnswerSheet() {
				this.$forceUpdate()
				this.showAnswerSheet = !this.showAnswerSheet
			},
			onAnswerPanel(index) {
				this.currentNum = index + 1

			},
			getExamList() {
				startExam({
					id: this.testPaperId,
					userId: this.userId,
				}).then(s => {
					if (s.code === 20000) {
						this.examList = s.data
						this.examList = this.examList.map(item => {
							return {
								...item,
								stuAnswer: ''
							}
						})
					} else {
						uni.showToast({
							title: s.message,
							icon: "none"
						})
					}
				})
			},
			touchStart(event) { // 手指触摸屏幕时触发，有一个手指放在屏幕上也会触发
				this.startX = event.changedTouches[0].pageX // 触摸目标在页面中的X坐标
				// console.log('开始触摸：', this.startX);
			},
			touchEnd(event) { // 手指离开屏幕时触发
				// 获取滑动距离
				const moveX = event.changedTouches[0].pageX - this.startX
				// console.log("moveX", moveX);
				// 判断滑动方向
				if (moveX < -100 && this.currentNum <= this.examList.length) {
					// 【下一题】 判断大幅度左滑且不是最后一题
					if (this.examList.length === this.currentNum) {
						uni.showToast({
							title: '当前是最后一题',
							icon: 'none',
							duration: 1500
						})
					}
					this.preNextClick(1)
				} else if (moveX > 100 && this.currentNum != 0) {
					// 【上一题】 判断大幅度右滑且不是第一题
					this.preNextClick(-1)
				}
			},
		},
		watch: {
			userAnswer: {
				handler(old, news) {
					// console.log("watch userAnswer old,news", old, news);
				},
				deep: true
			},
			currentQuestion(value) { //题目信息
				if (value.type == 1) {
					if (value.stuAnswer.length > 0) {
						this.userAnswer.answer = value.stuAnswer
					} else {
						this.userAnswer.answer = ''
					}
				}
				if (value.type == 2) {
					if (value.stuAnswer.length > 0) {
						this.userAnswer.answer = value.stuAnswer
					} else {
						this.userAnswer.answer = []
					}
				}
				if (value.type == 3) {
					if (value.stuAnswer.length > 0) {
						this.userAnswer.answer = value.stuAnswer
					} else {
						this.userAnswer.answer = ''
					}
				}
			}
		},
		computed: {
			currentQuestion() {
				return this.getCurrentQuestion()
			},
			questionType() {
				return {
					1: '单选',
					2: '多选',
					3: '判断'
				} [this.currentQuestion.type]
			},
			userAnswerParams() {
				const result = {};
				this.examList.forEach((item) => {
					result[item.id] = item.stuAnswer
				})
				return result
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		width: 100%;
		position: relative;
		background: #F2F2F2;
		height: calc(100vh - 44px);
	}

	.main_content {
		width: 100%;
		background: #fff;
		transform: translateX(0);
		transition: transform 0.5s ease;

		// height: 400rpx;
		.u-swiper {
			height: 800rpx;
		}

		.questTypeContent {
			height: 41px;
			line-height: 41px;
			padding: 0 14px;
			box-sizing: border-box;
			background: #fff;

			.questionType {
				height: 28px;
				line-height: 28px;
				font-size: 13px;
				color: #78A3FD;
				background: #EEF2FF;
				padding: 0rpx 15rpx;
				box-sizing: border-box;
				border-radius: 10rpx;
			}

			.questionAmount {
				font-size: 12px;
				color: #999;

				.activeClr {
					color: #3888FF;
					font-size: 14px;
				}
			}
		}

		.questionContent {
			padding: 14px;
			box-sizing: border-box;
			font-size: 34rpx;
			box-shadow: 4px 4px 10px #EEF2FF inset;

			.questionTitle {
				margin-bottom: 24rpx;
				line-height: 1.5;
			}

			.answer_item {
				margin-top: 20rpx;
			}
		}
	}

	.bottom_area {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		box-sizing: border-box;
		padding: 10rpx 30rpx;
		background: #fff;

		.collection {
			margin-right: 20rpx;
			text-align: center;

			image {
				width: 50rpx;
				height: 50rpx;

			}
		}

		.answerSheet {
			margin-right: 20rpx;
			text-align: center;

			image {
				width: 50rpx;
				height: 50rpx;

			}
		}

		.submitBtn {}
	}

	.time {
		@include flex;
		align-items: center;
		margin-left: 15rpx;

		&__custom {
			margin-top: 4px;
			width: 28px;
			height: 28px;
			background-color: red;
			border-radius: 4px;
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			justify-content: center;
			align-items: center;

			&__item {
				color: #fff;
				font-size: 12px;
				text-align: center;
			}
		}

		&__doc {
			color: red; //$u-primary
			padding: 0px 4px;
		}

		&__item {
			color: #606266;
			font-size: 15px;
			margin-right: 4px;
		}
	}

	.time_container {
		box-sizing: border-box;
		padding: 30rpx;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		background: #fff;
	}

	.answerPanel {
		transition: right 0.3s ease;
		z-index: 1001;
		background-color: white;
		box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
		padding: 40rpx;
		box-sizing: border-box;

		.card_title {
			font-weight: bold;
			color: #0d0e10;
			text-align: left;
			padding-left: 10px;
			font-size: 14px;
			border-left: #3888FF 3px solid;
			box-sizing: border-box;
		}

		.titleTxt {
			font-size: 12px;
			color: #9cb2cd;
			text-indent: 0;
			margin-left: 5px;
		}
	}

	.titleText {
		position: relative;
		display: inline-block;
		border: 1px solid #bfbfbf;
		width: 12px;
		height: 12px;
		text-indent: 0;
		margin-left: 3px;
		top: 2px;
	}

	.titleAnswered {
		border: 1px solid #3888FF;
		background: #3888FF;
	}

	.card_content {
		padding: 20px 0 10px 0;
		box-sizing: border-box;
		overflow-y: auto;
		min-height: 260px;
		max-height: 400px;
	}

	.picker-item {
		cursor: pointer;
		width: 38px;
		height: 38px;
		line-height: 38px;
		text-align: center;
		border: 1px solid #dddddd;
		border-radius: 5px;
		background: #ffffff;
		-webkit-user-select: none;
		-moz-user-select: none;
		-ms-user-select: none;
		user-select: none;
		float: left;
		margin: 4px 6px;
		position: relative;
		overflow: hidden;

		&.normal {
			background: #3888FF;
			color: #fff;
		}
	}

	/deep/ .u-radio__text,
	/deep/ uni-text {
		font-size: 18px !important;
		line-height: 18px !important;
	}
</style>